package com.adgox.tiantianbiting.listen.index;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.adapter.CollectAdapter;
import com.adgox.tiantianbiting.adapter.RecommendAdapter;
import com.adgox.tiantianbiting.base.BasicFragment;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.HistoryBean;
import com.adgox.tiantianbiting.bean.PageBean;
import com.adgox.tiantianbiting.bean.ShareUrlBean;
import com.adgox.tiantianbiting.bean.SubProgramBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.home.programDetail.ProgramDetailActivity;
import com.adgox.tiantianbiting.listen.buy_already.BuyAlreadyActivity;
import com.adgox.tiantianbiting.listen.find_like.FindLikeActivity;
import com.adgox.tiantianbiting.listen.history.HistoryActivity;
import com.adgox.tiantianbiting.mine.login.LoginActivity;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.utils.ApiConstant;
import com.adgox.tiantianbiting.utils.DialogUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rae.swift.session.SessionManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class ListenFragment extends BasicFragment implements ListenContract.View, CollectAdapter.onItemClickListener, View.OnClickListener, RecommendAdapter.onItemClickListener {


    @BindView(R.id.indicator_recommend)
    View indicatorRecommend;
    @BindView(R.id.indicator_collect)
    View indicatorCollect;
    @BindView(R.id.rv_history)
    RecyclerView rvHistory;
    @BindView(R.id.rv_collect)
    RecyclerView rvCollect;
    Unbinder unbinder;
    @BindView(R.id.ll_empty)
    LinearLayout llEmpty;
    @BindView(R.id.rv_recommend)
    RecyclerView rvRecommend;
    private ListenContract.Presenter mPresenter;
    private int maxPage = 10;
    private int currentHistoryPage = 1;
    private int currentCollectPage = 1;


    private List<SubProgramBean> newCollectList = new ArrayList<>();
    private List<SubProgramBean> recommendList = new ArrayList<>();
    private int totalHistoryPages;
    private int totalCollectPages;
    //    private boolean isRefresh = true;//是否需要刷新
    private RecommendAdapter recommendAdapter;
    private CollectAdapter newCollectAdapter;
    private int userId;
    private int clickPosition;
    private Dialog findLikeDialog;

    public static ListenFragment newInstance() {
        return new ListenFragment();
    }

    @Override
    public int getLayoutId(Bundle var1) {
        return R.layout.fragment_listen;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new ListenPresenterImpl(this);
    }

    private void init() {
        if (SessionManager.getDefault().isLogin()) {
            int id = ((UserInfo) SessionManager.getDefault().getUser()).getId();
            userId = id;
            if (newCollectAdapter != null) newCollectAdapter.clear();
            if (recommendAdapter != null) recommendAdapter.clear();
            newCollectList.clear();
            recommendList.clear();
            mPresenter.getCollect(currentCollectPage, maxPage, userId);
            mPresenter.getRecommend(userId);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (mPresenter == null) return;
        if (!SessionManager.getDefault().isLogin()) {
            newCollectList.clear();
            recommendList.clear();
            if (newCollectAdapter != null) newCollectAdapter.clear();
            if (recommendAdapter != null) recommendAdapter.clear();
            rvRecommend.setVisibility(View.GONE);
            rvCollect.setVisibility(View.GONE);
            llEmpty.setVisibility(View.VISIBLE);
            return;
        }
        init();

    }

    @Override
    public void onResume() {
        super.onResume();
        if (mPresenter == null) return;
        if (!SessionManager.getDefault().isLogin()) {
            newCollectList.clear();
            recommendList.clear();
            if (newCollectAdapter != null) newCollectAdapter.clear();
            if (recommendAdapter != null) recommendAdapter.clear();
            rvRecommend.setVisibility(View.GONE);
            rvCollect.setVisibility(View.GONE);
            llEmpty.setVisibility(View.VISIBLE);
            return;
        }
        init();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        rvHistory.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                if (!rvHistory.canScrollVertically(1)) {
//                    if (currentHistoryPage < totalHistoryPages) {
//                        currentHistoryPage++;
//                        showLoading();
//                        mPresenter.getHistroy(currentHistoryPage, maxPage, userId);
//                    } else {
//                        Toast.makeText(getContext(), "没有更多了", Toast.LENGTH_SHORT).show();
//                    }
//
//                }
//            }
//        });

        rvCollect.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (!rvCollect.canScrollVertically(1)) {
                    if (currentCollectPage < totalCollectPages) {
                        currentCollectPage++;
                        showLoading();
                        mPresenter.getCollect(currentCollectPage, maxPage, userId);
                    } else {
                        Toast.makeText(getContext(), "没有更多了", Toast.LENGTH_SHORT).show();
                    }

                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void setPresenter(ListenContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @OnClick(R.id.tv_recommend)
    public void onRecommendClicked() {
        indicatorCollect.setVisibility(View.INVISIBLE);
        indicatorRecommend.setVisibility(View.VISIBLE);
        rvCollect.setVisibility(View.GONE);
        rvHistory.setVisibility(View.GONE);
        rvRecommend.setVisibility(View.VISIBLE);

        if (recommendList.size() == 0) {
            llEmpty.setVisibility(View.VISIBLE);
            rvRecommend.setVisibility(View.GONE);
        } else {
            rvRecommend.setVisibility(View.VISIBLE);
            llEmpty.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.tv_collect)
    public void onCollectClicked() {
        indicatorRecommend.setVisibility(View.INVISIBLE);
        indicatorCollect.setVisibility(View.VISIBLE);
        rvHistory.setVisibility(View.GONE);
        rvRecommend.setVisibility(View.GONE);
        rvCollect.setVisibility(View.VISIBLE);

        if (newCollectList.size() == 0) {
            llEmpty.setVisibility(View.VISIBLE);
            rvCollect.setVisibility(View.GONE);
        } else {
            llEmpty.setVisibility(View.GONE);
            rvCollect.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onSetHistory(PageBean<HistoryBean> list) {
//        if (list == null || list.getData() == null || list.getData().size() == 0) {
//            Toast.makeText(getActivity(), "获取数据失败", Toast.LENGTH_SHORT).show();
//            return;
//        }
//
//        totalHistoryPages = list.getTotalPages();
//        historyList.addAll(list.getData());
//
//
//        if (historyAdapter == null) {
//            LinearLayoutManager manager = new LinearLayoutManager(getContext());
//            rvHistory.setLayoutManager(manager);
//            historyAdapter = new HistoryAdapter(list.getData(), getContext());
//            rvHistory.setAdapter(historyAdapter);
//        } else {
//            historyAdapter.addDatas(list.getData());
//            historyAdapter.notifyDataSetChanged();
//        }


    }

    public void showLoading() {
        DialogUtils.showLoadingDialog(getContext());
    }

    @Override
    public void onGetHistoryFailed(String msg) {
        llEmpty.setVisibility(View.VISIBLE);
        rvHistory.setVisibility(View.GONE);
        rvCollect.setVisibility(View.GONE);
    }

    @Override
    public void onSetCollect(PageBean<SubProgramBean> list) {
        if (list == null || list.getData() == null || list.getData().size() == 0) {
            Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_SHORT).show();
            return;
        }

        totalCollectPages = list.getTotalPages();
        newCollectList.addAll(list.getData());
//        collectList.addAll(list.getData());


        if (newCollectAdapter == null) {
            LinearLayoutManager manager = new LinearLayoutManager(getContext());
            rvCollect.setLayoutManager(manager);
            newCollectAdapter = new CollectAdapter(list.getData());
            rvCollect.setAdapter(newCollectAdapter);
            newCollectAdapter.setOnItemClickListener(this);
        } else {
            newCollectAdapter.addDatas(list.getData());
            newCollectAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetCollectFailed(String msg) {
        llEmpty.setVisibility(View.VISIBLE);
        rvRecommend.setVisibility(View.GONE);
        rvCollect.setVisibility(View.GONE);
    }

    @Override
    public void onSetRecommend(List<SubProgramBean> list) {
        recommendList = list;
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        rvRecommend.setLayoutManager(manager);
        RecommendAdapter recommendAdapter = new RecommendAdapter(list);
        recommendAdapter.setOnItemClickListener(this);
        rvRecommend.setAdapter(recommendAdapter);
    }

    @Override
    public void onGetRecommendFailed(String msg) {

    }

    @Override
    public void onItemClick(View view, CollectAdapter.ViewName viewName, int position) {
        if (viewName == CollectAdapter.ViewName.FINDLIKE) {
            clickPosition = position;
            popFindLikeDialog(view);
        } else if (viewName == CollectAdapter.ViewName.ITEM) {
            Intent intent = new Intent(getActivity(), ProgramDetailActivity.class);
            intent.putExtra("programId", newCollectList.get(position).getId());
            intent.putExtra("programName", newCollectList.get(position).getTitle());
            startActivity(intent);
        }
    }

    private void popFindLikeDialog(View view) {
        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.dialog_find_like, null);
        findLikeDialog = new Dialog(getContext(), R.style.TransparentDialog);
        findLikeDialog.setContentView(inflate);

        FrameLayout flFind = findLikeDialog.findViewById(R.id.fl_find);
        FrameLayout flTop = findLikeDialog.findViewById(R.id.fl_top);
        FrameLayout flCollect = findLikeDialog.findViewById(R.id.fl_collect);
        FrameLayout flShare = findLikeDialog.findViewById(R.id.fl_share);

        flFind.setOnClickListener(this);
        flTop.setOnClickListener(this);
        flCollect.setOnClickListener(this);
        flShare.setOnClickListener(this);

        Window window = findLikeDialog.getWindow();
        window.setGravity(Gravity.RIGHT | Gravity.TOP);
        WindowManager.LayoutParams attributes = window.getAttributes();
        int[] positions = new int[2];
        view.getLocationOnScreen(positions);
        attributes.y = positions[1];
        attributes.x = 100;
        window.setAttributes(attributes);
        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        findLikeDialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_find:
                Intent intent = new Intent(getActivity(), FindLikeActivity.class);
                intent.putExtra("categoryId", newCollectList.get(clickPosition).getCategoryId());
                startActivity(intent);
                if (findLikeDialog != null) findLikeDialog.dismiss();
                break;
            case R.id.fl_top:
                //收藏置顶
                setTop();
                if (findLikeDialog != null) findLikeDialog.dismiss();
                break;
            case R.id.fl_collect:
                HashMap<String, Object> map = new HashMap<>();
                map.put("programId", newCollectList.get(clickPosition).getId());
                map.put("status", 2);
                map.put("seasonId", 1);
                map.put("userId", userId);
                Gson gson = new Gson();
                String s = gson.toJson(map);
                cancelCollect(s);
                findLikeDialog.dismiss();
                break;
            case R.id.fl_share:
                share();
                findLikeDialog.dismiss();
                break;
        }
    }

    private void share() {
        OkGo.<BaseResponseBean<ShareUrlBean>>get(ApiConstant.BASE_URL + ApiConstant.GET_SHARE_URL)
                .params("flg", "go_download")
                .execute(new JsonCallback<BaseResponseBean<ShareUrlBean>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<ShareUrlBean>> response) {
                        if ("0".equals(response.body().getCode()) && response.body().getData() != null) {
                            DialogUtils.showShareDialog(getContext(), response.body().getData().getLocation());
                        } else {
                            Toast.makeText(getContext(), "获取分享信息失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void cancelCollect(String s) {
        OkGo.<BaseResponseBean<String>>post(ApiConstant.BASE_URL + ApiConstant.CANCEL_COLLECT)
                .upJson(s)
                .execute(new JsonCallback<BaseResponseBean<String>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<String>> response) {
                        DialogUtils.dismiss();
                        if ("0".equals(response.body().getCode())) {
                            init();
                        } else {
                            Toast.makeText(getActivity(), "操作失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    private void setTop() {
        OkGo.<BaseResponseBean<String>>get(ApiConstant.BASE_URL + ApiConstant.SET_TOP)
                .params("userId", userId)
                .params("programId", newCollectList.get(clickPosition).getId())
                .execute(new JsonCallback<BaseResponseBean<String>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<String>> response) {
                        if ("0".equals(response.body().getCode())) {
                            init();
                        } else {
                            Toast.makeText(getActivity(), "操作失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    public void onItemClick(View view, RecommendAdapter.ViewName viewName, int position) {
        if (viewName == RecommendAdapter.ViewName.COLLECT) {
            DialogUtils.showLoadingDialog(getContext());
            HashMap<String, Object> map = new HashMap<>();
            map.put("programId", recommendList.get(position).getId());
            map.put("status", 2);
            map.put("seasonId", 1);
            map.put("userId", userId);
            Gson gson = new Gson();
            String s = gson.toJson(map);
            if (recommendList.get(position).getMarkStatus() == 0) {
                cancelCollect(s);
            } else {
                addCollect(s);
            }
        } else if (viewName == RecommendAdapter.ViewName.ITEM) {
            Intent intent = new Intent(getActivity(), ProgramDetailActivity.class);
            intent.putExtra("programId", recommendList.get(position).getId());
            intent.putExtra("programName", recommendList.get(position).getTitle());
            startActivity(intent);
        }
    }

    private void addCollect(String s) {
        OkGo.<BaseResponseBean<String>>post(ApiConstant.BASE_URL + ApiConstant.ADD_COLLECT_AND_HISTORY)
                .upJson(s)
                .execute(new JsonCallback<BaseResponseBean<String>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<String>> response) {
                        DialogUtils.dismiss();
                        if ("0".equals(response.body().getCode())) {
                            init();
                        } else {
                            Toast.makeText(getActivity(), "操作失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @OnClick(R.id.rl_history)
    public void onHistoryClicked() {
        if (SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(getActivity(), HistoryActivity.class));
        } else {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }
    }

    @OnClick(R.id.rl_buy)
    public void onBuyClicked() {
        if (SessionManager.getDefault().isLogin()) {
            startActivity(new Intent(getActivity(), BuyAlreadyActivity.class));
        } else {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }
    }

    @OnClick(R.id.rl_download)
    public void onDownloadClicked() {
        Toast.makeText(getActivity(), "暂未开放，敬请期待", Toast.LENGTH_SHORT).show();
    }

    @OnClick(R.id.rl_shelf)
    public void onShelfClicked() {
        Toast.makeText(getActivity(), "暂未开放，敬请期待", Toast.LENGTH_SHORT).show();
    }
}
